/** @jsxImportSource @emotion/react */
//import { jsx } from "@emotion/react";
import * as React from "react";
import {
    List,
    ListItem,
    Avatar,
    IconButton,
    Button,
    MenuList,
    useTheme,
    IconMoreVertical,
    Skeleton, MenuItem, IconPackage, IconRefButton, useToast, DdMenuItem, VerticalMenu
} from "customize-easy-ui-component";

//import {  usePaginateQueryDevice,  } from "./db";
import { Link as RouterLink } from "../routing/Link";
import {useContext, useEffect} from "react";
import { useInView } from 'react-intersection-observer'
import RoutingContext from "../routing/RoutingContext";
import {usePaginationFragment, useRefetchableFragment} from "react-relay/hooks";
import { PipingUnitListInner$key } from "./__generated__/PipingUnitListInner.graphql";
import {VariablesOf} from "relay-runtime";
//import { PullToRefresh,PullDownContent,RefreshContent,ReleaseContent } from "react-js-pull-to-refresh";
//import { usePrevious } from "customize-easy-ui-component/esm/Hooks/previous";
const graphql = require("babel-plugin-relay/macro");

interface PipingUnitListInnerProps {
  filter: any   //用props参数看看
    eqps: PipingUnitListInner$key;
}
export const PipingUnitListInner: React.FunctionComponent<
    PipingUnitListInnerProps
> = (props: PipingUnitListInnerProps) => {
  const theme = useTheme();
  const { history } = useContext(RoutingContext);
    const toast = useToast();
  //useRefetchableFragment不能用在普通对象模型上;
  //提取查询到路由器loadMore　,refetch  devicesFind, loading 参数{filter}
    //很特殊的！ DeviceListInnerRefetchQuery 直接作为入口，没有前面的查询可嵌套的,Query直接套上.
    //要用usePaginationFragment必须上connection应答类型，接口须有first或last参数的,
    //上级usePreloaded定义了参数after，下级fragment就不再要定义@argumentDefinitions(after: )参数了。
    //参数@argumentDefinitions( #states: { type: "[IssueState!]", defaultValue: OPEN })
    //参数若是只放在这一层定义而上级那层没定义的将会导致自动生成文件接口定义没有这里的参数，所以失败啊。
    //@argumentDefinitions()里面参数多定义了没用到也不会报错的。 loadNext(,UNSTABLE_extraVariables)
    //这里@argumentDefinitions()里不能和上层次共同定义一个同名字参数的，编译报错。
    //参数若仅在这里定义而上层没有定义，导致主查询提前装载数据失败，Refetch才会有该参数，重新查询能查询正常，奇异！非要点击refetch才能获得正常数据那还叫提前装载,refetch等于loadQuery(var)。
    /*若是把接口node(id: ID!): Node修改为node(id: ID, routeVal: String): Node这里会报错：
        Invalid use of @refetchable on fragment 'PipingUnitListInner',
        check that your schema defines a `Node { id: ID }` interface and has a `node(id: ID):Node` field on the query type (the id argument may also be non-null).
     底下的graphql fragment on Pipeline是这么定义的:"
        @refetchable(queryName: "PipingUnitListInnerRefetchQuery") {
                cell_list(after:$after,first:$first)
              @connection(key: "Pipeline_cell_list") {  edges    "
    需要把@refetchable(queryName: "PipingUnitListInnerRefetchQuery") 这个前缀描述删除掉后就能让Relay编译通过了！。
    @refetchable编译通过以后才会生成PipingUnitListInnerRefetchQuery.graphql.ts查询文件的，对应于refetch的命令通道relay要调用的底层接口文件封装。
    */
  const { data, refetch , loadNext,hasNext,isLoadingNext} = usePaginationFragment(
      graphql`
        fragment PipingUnitListInner on Pipeline
        @refetchable(queryName: "PipingUnitListInnerRefetchQuery") {
            cell_list(after:$after,first:$first)
          @connection(key: "Pipeline_cell_list") {
              edges {
                  node {
                      id code ust name 
                      pipe{id}
                  }
              }
          }
        }
      `,
      props.eqps,
  );
  const { cell_list }=data;
    const devicesFind=cell_list?.edges;

  /*
  const { data,refetch, hasNext, loadNext, isLoadingNext } = usePaginationFragment(
      graphql`
        fragment IssueDetailComments_issue on Issue
        @argumentDefinitions(
          cursor: { type: "String" }
          count: { type: "Int", defaultValue: 10 }
        )
        @refetchable(queryName: "IssueDetailCommentsQuery") {
          comments(after: $cursor, first: $count)
        }
      `,
      props.issue,
  );
  */

  //上面这个副作用必须 加usersFind，否则无法继续处理后端数据带来的必要的UI反馈变化。
  const refLsize = React.useRef(0);
  const [refMore, acrossMore] = useInView({threshold: 0});
  //后端返回了loading变动=会更新整个DeviceList组件，同时也执行updateQuery: ()=>{}回调更新数据。
    //     offset: devicesFind.length,
  /*const toLoadMore = React.useCallback(
    async () => {
      refLsize.current=devicesFind?.length || 0;    //看看有没有新增加项目
      devicesFind && loadNext(3);
    },
    [loadNext ,devicesFind]
  );*/

  useEffect( () => { acrossMore && hasNext
              &&  loadNext(8,{
                      onComplete: (error) =>  {
                          if(error){
                              console.log("列表报错 data=", data );
                              toast({
                                  title: "返回了",
                                  subtitle: ""+error,
                                  intent: "error"
                              });
                          }
                      }
                  });
          },
        [acrossMore, hasNext,loadNext,data,toast]);

  //console.log("霉$R1变 refLsize=",refLsize.current,"devicesFind=",devicesFind?.length);
    //界面没提供命令入口点
  const callRefetch = React.useCallback(() => {
        //setHasMore(true);
       // refetch( filter );
      refetch({...props.filter}, {fetchPolicy: 'store-or-network'})
  }, [refetch, props.filter]);

  //有些场合不需要做refetch就能触发，可能被appollo自动优化。变化驱动链条query＝>filter
  //有问题：refetch这个时间的入口参数filter还是捕获的旧的，须延迟一个render()后再去做。
  /*React.useEffect(() => {
    //console.log("callRefetch重做归零filter=",filter,"devicesFind=",devicesFind);
    callRefetch();
  }, [callRefetch]);
  */
    const {save, field, reurl, p1field}= window.history.state?.state??{};      //通用伪对话框传递格式
  //控件<Stack 是堆叠式的，像导航条；适用同一个模板显示只需上级给下级参数调整的场景。根据上一叠页面选择触发状态relation给下一叠参数来控制下一级显示；更多嵌套很困难。
  return (
    <React.Fragment>
            <List>
              {isLoadingNext && (
                <React.Fragment>
                  <ListItem
                    interactive={false}
                    contentBefore={
                      <Skeleton
                        css={{
                          width: "32px",
                          height: "32px",
                          borderRadius: "50%"
                        }}
                      />
                    }
                    primary={<Skeleton css={{ maxWidth: "160px" }} />}
                  />
                  <ListItem
                    interactive={false}
                    contentBefore={
                      <Skeleton
                        css={{
                          width: "32px",
                          height: "32px",
                          borderRadius: "50%"
                        }}
                      />
                    }
                    primary={<Skeleton css={{ maxWidth: "200px" }} />}
                  />
                </React.Fragment>
              )}

              {
                devicesFind?.map((hit,i) => (
                    <ListItem  key={hit?.node?.id}
                           onPress={(e) => {
                                history.push(`/pipeline/${hit?.node?.pipe?.id}/${hit?.node?.id}`, {save,field,reurl,p1field});
                            }}
                              contentBefore={
                                <React.Fragment>
                                  <Avatar size="xs" name={'单'}/>
                                  <Avatar size="xs" name={'元'}/>
                                </React.Fragment>
                              }
                              primary={`${hit?.node?.code}`}
                              contentAfter={
                                  <VerticalMenu>
                                      <DdMenuItem label="加个管道单元"
                                                  onClick={(e) => {
                                                      history.push(`/pipeline/${hit?.node?.pipe?.id}/new`);
                                                  }}/>
                                      <DdMenuItem label="功能待续"
                                                  onClick={(e) => {
                                                      //await setRepId(recipe.id);    handleDelete(recipe.id)
                                                  }}/>
                                  </VerticalMenu>
                              }
                    />
              ))}

            </List>

              <div
                css={{
                  textAlign: "center",
                  marginBottom: theme.spaces.md,
                  marginTop: theme.spaces.md
                }}
              >
                { (refLsize.current!==devicesFind?.length)  &&  (
                  <div>
                    <Button disabled={isLoadingNext} onPress={ () =>{
                        loadNext(15,{
                           onComplete: (error) =>  {
                                if(error){
                                    toast({
                                        title: "返回了",
                                        subtitle: ""+error,
                                        intent: "error"
                                    });
                                }
                            }
                        });     //虽然引用表现是异步的，但还是需要某些步骤需要同步执行的，只能说是其内部深度嵌套了个Promise()。
                      //console.log(`按拉扯获取took ${duration}ms`);　//异步处理了，这里实际耗时也不短暂122ms; 可能因为loading要同步首先设置的。
                    } }>
                      按，拉扯获取更多......
                    </Button>
                  </div>
                )}
                {(refLsize.current===devicesFind?.length)  &&　<React.Fragment>
                      <span>嘿，没有更多了</span>
                  </React.Fragment>
                }
              </div>
              <div  ref={refMore}  css={{height: "1px"}}> </div>
    </React.Fragment>
  );
};
